﻿using System;
using AutoStopApp.Core;
using AutoStopApp.ServerControls;
using AutoStopData.BussinessLogic;
using Telerik.Web.UI;

namespace AutoStopApp.Controls
{
    public partial class TripGrid : AjaxUserControl
    {
        public CustomGrid GridInstance { get { return rgrInstance; } }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += PageLoad;
        }

        void PageLoad(object sender, EventArgs e)
        {
            var page = (AjaxPage)Page;
            InitializeAjaxControls(page.AjaxManager, page.LoadingPanel);
            AddAjaxSetting(rgrInstance, rgrInstance);
        }

        protected void UserRatingRate(object sender, EventArgs e)
        {
            var userRating = (RadRating)sender;
            var dataItem = (GridDataItem)userRating.Parent.Parent;

            var currentSession = SessionProvider.CurrentSession;
            if (currentSession != null && dataItem != null)
            {
                var tripId = new Guid(dataItem.Cells[2].Text);
                var userRatingValue = userRating.Value;
                Trips.AddRating(tripId, currentSession.User.UserId, userRatingValue);
            }
            rgrInstance.Rebind();
        }

        public Guid? GetCurrentUserId()
        {
            var currentSession = SessionProvider.CurrentSession;
            var currentUserId = currentSession == null ? (Guid?)null : currentSession.User.UserId;
            return currentUserId;
        }
    }
}